package com.avic.system.controller;

import com.avic.system.common.constant.SystemLogConstant;
import com.avic.system.common.constant.UserConstant;
import com.avic.system.common.util.AssertUtil;
import com.avic.system.common.util.ex.BizErrorCode;
import com.avic.system.common.util.lang.BaseResponse;
import com.avic.system.common.util.lang.ServiceCallBack;
import com.avic.system.controller.info.SystemRoleInfo;
import com.avic.system.controller.request.CreateSystemRoleReq;
import com.avic.system.controller.request.ModifySystemRoleReq;
import com.avic.system.controller.request.SaveRolePermissionReq;
import com.avic.system.controller.result.CreateSystemRoleRes;
import com.avic.system.controller.result.GetSystemRolesRes;
import com.avic.system.dal.model.SystemRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/system/role")
@Api(tags = "系统角色", description = "获取所有角色数据&新增系统角色数据&修改角色&删除角色&保存角色权限接口")
public class SystemRoleController extends AbstractFacadeImpl {

    @ApiOperation(value = "获取系统角色列表数据，不分页")
    @GetMapping("list")
    public GetSystemRolesRes getSystemRoles() {
        log.info("获取系统角色数据--getSystemRoles");
        final GetSystemRolesRes result = new GetSystemRolesRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

            }

            @Override
            public void doService() throws Exception {
                List<SystemRole> systemRoles = systemRoleService.getSystemRoles();
                if (null != systemRoles && systemRoles.size() > 0) {
                    log.info("获取到角色数量 {} 条", systemRoles.size());
                    List<SystemRoleInfo> systemRoleInfos = new ArrayList<>();
                    systemRoles.forEach(systemRole -> {
                        SystemRoleInfo systemRoleInfo = new SystemRoleInfo();
                        systemRoleInfo.setRoleId(systemRole.getId());
                        systemRoleInfo.setRoleName(systemRole.getRoleName());
                        systemRoleInfos.add(systemRoleInfo);
                    });
                    result.setRoles(systemRoleInfos);
                }
                result.setSuccess(true);
            }

        });
    }

    @ApiOperation(value = "新增系统角色数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createSystemRoleReq", required = true, dataType = "CreateSystemRoleReq")
    })
    @ApiResponses({
            @ApiResponse(code = 100013, message = "角色名存在"),
    })
    @PostMapping
    public CreateSystemRoleRes createSystemRole(@RequestBody CreateSystemRoleReq createSystemRoleReq,
                                                @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("新增系统角色数据--createSystemRole");
        final CreateSystemRoleRes result = new CreateSystemRoleRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(createSystemRoleReq.getRoleName(), "roleName is blank");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {

                SystemRole systemRole = new SystemRole();
                systemRole.setRoleName(createSystemRoleReq.getRoleName());
                String roleId = systemRoleService.createSystemRole(systemRole);
                log.info("成功新增 ID= {} 的角色数据", roleId);
                result.setRoleId(roleId);

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.CREATE_SYSTEM_ROLE_STRING, roleId, createSystemRoleReq.getRoleName()), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "修改系统角色数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modifySystemRoleReq", required = true, dataType = "ModifySystemRoleReq")
    })
    @ApiResponses({
            @ApiResponse(code = 100013, message = "角色名存在"),
    })
    @PutMapping
    public BaseResponse updateSystemRole(@RequestBody ModifySystemRoleReq modifySystemRoleReq,
                                         @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("更新系统角色数据--updateSystemRole");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(modifySystemRoleReq.getRoleId(), "roleId is blank");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {

                log.info("更新：{} 的角色数据", modifySystemRoleReq.getRoleId());
                SystemRole systemRole = new SystemRole();
                systemRole.setId(modifySystemRoleReq.getRoleId());
                systemRole.setRoleName(modifySystemRoleReq.getRoleName());
                systemRoleService.updateSystemRole(systemRole);

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.UPDATE_SYSTEM_ROLE_STRING, modifySystemRoleReq.getRoleId(), modifySystemRoleReq.getRoleName()), currentUserId);
                result.setSuccess(true);
            }


        });
    }

    @ApiOperation(value = "删除系统角色数", notes = "逻辑删除，数据依然保留")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", paramType = "path", value = "角色ID", required = true)
    })
    @DeleteMapping("/{roleId}")
    public BaseResponse delete(@PathVariable("roleId") String roleId,
                               @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("删除系统角色数据--delete");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(roleId, "roleId");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {
                log.info("删除：{} 的角色数据", roleId);

                systemRoleService.deleteSystemRole(roleId);

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.DELETE_SYSTEM_ROLE_STRING, roleId), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "保存角色的权限数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "saveRolePermissionReq", required = true, dataType = "SaveRolePermissionReq")
    })
    @ApiResponses({
            @ApiResponse(code = 100012, message = "角色数据不存在")
    })
    @PutMapping("saveRolePermission")
    public BaseResponse saveRolePermission(@RequestBody SaveRolePermissionReq saveRolePermissionReq,
                                           @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("保存角色的权限数据--saveRolePermission");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(saveRolePermissionReq.getRoleId(), "roleId");
                AssertUtil.isNotNull(saveRolePermissionReq.getPermissionIds(), BizErrorCode.PARAM_ERROR, "permissionIds");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {
                log.info("保存角色ID= {}, 权限数量 ={}", saveRolePermissionReq.getRoleId(), saveRolePermissionReq.getPermissionIds().size());
                systemRoleService.saveRolePermission(saveRolePermissionReq.getRoleId(), saveRolePermissionReq.getPermissionIds());
                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.SAVE_SYSTEM_ROLE_STRING,
                                saveRolePermissionReq.getRoleId(), saveRolePermissionReq.getPermissionIds().toString()), currentUserId);
                result.setSuccess(true);
            }
        });
    }
}
